<template>
  <el-card class="template-list">
    <!-- 头部区域 -->
    <template #header>
      <page-header title="权限模板">
        <el-button type="primary" @click="handleAdd">新建模板</el-button>
      </page-header>
    </template>

    <!-- 搜索区域 -->
    <div class="search-bar mb-4">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="模板名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="filteredData"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="name" label="模板名称" min-width="150" />
      <el-table-column prop="code" label="模板编码" min-width="120" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="is_system" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.is_system ? 'success' : ''">
            {{ row.is_system ? '系统预设' : '自定义' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            link
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="!row.is_system"
            type="danger"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="currentTemplate ? '编辑模板' : '新建模板'"
      v-model="dialogVisible"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板编码" prop="code">
          <el-input 
            v-model="formData.code" 
            placeholder="请输入模板编码"
            :disabled="!!currentTemplate"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="2"
            placeholder="请输入模板描述"
          />
        </el-form-item>

        <!-- 权限配置 -->
        <el-divider>权限配置</el-divider>
        
        <!-- 系统权限 -->
        <el-form-item label="系统权限" prop="permissions.system">
          <el-checkbox-group v-model="formData.permissions.system">
            <el-checkbox label="*">所有权限</el-checkbox>
            <el-checkbox label="view">查看</el-checkbox>
            <el-checkbox label="add">新增</el-checkbox>
            <el-checkbox label="edit">编辑</el-checkbox>
            <el-checkbox label="delete">删除</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 业务权限 -->
        <el-form-item label="业务权限" prop="permissions.business">
          <el-checkbox-group v-model="formData.permissions.business">
            <el-checkbox label="*">所有权限</el-checkbox>
            <el-checkbox label="view">查看</el-checkbox>
            <el-checkbox label="export">导出</el-checkbox>
            <el-checkbox label="import">导入</el-checkbox>
            <el-checkbox label="print">打印</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 数据权限 -->
        <el-form-item label="数据范围" prop="permissions.data.scope">
          <el-radio-group v-model="formData.permissions.data.scope">
            <el-radio label="all">所有数据</el-radio>
            <el-radio label="department">本部门数据</el-radio>
            <el-radio label="self">个人数据</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="字段权限" prop="permissions.data.fields">
          <el-checkbox-group v-model="formData.permissions.data.fields">
            <el-checkbox label="*">所有字段</el-checkbox>
            <el-checkbox label="basic">基础字段</el-checkbox>
            <el-checkbox label="sensitive">敏感字段</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import PageHeader from '@/components/PageHeader.vue'
import { permissionTemplateApi } from '@/api/permissionTemplateApi'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 过滤后的数据
const filteredData = computed(() => {
  let result = [...tableData.value]
  
  if (searchForm.name) {
    result = result.filter(item => 
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  
  if (searchForm.status !== '') {
    result = result.filter(item => item.status === searchForm.status)
  }
  
  return result
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await permissionTemplateApi.getList()
    if (res.code === 200) {
      tableData.value = res.data
    }
  } catch (error) {
    console.error('Load templates error:', error)
    ElMessage.error('加载模板列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  // 使用计算属性自动过滤
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
}

// 表单数据
const dialogVisible = ref(false)
const currentTemplate = ref(null)
const formRef = ref(null)
const formData = reactive({
  name: '',
  code: '',
  description: '',
  permissions: {
    system: [],
    business: [],
    data: {
      scope: 'department',
      fields: []
    }
  },
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入模板编码', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_-]+$/, message: '只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  'permissions.system': [
    { required: true, message: '请选择系统权限', trigger: 'change' }
  ],
  'permissions.business': [
    { required: true, message: '请选择业务权限', trigger: 'change' }
  ],
  'permissions.data.scope': [
    { required: true, message: '请选择数据范围', trigger: 'change' }
  ],
  'permissions.data.fields': [
    { required: true, message: '请选择字段权限', trigger: 'change' }
  ]
}

// 新建模板
const handleAdd = () => {
  currentTemplate.value = null
  Object.assign(formData, {
    name: '',
    code: '',
    description: '',
    permissions: {
      system: [],
      business: [],
      data: {
        scope: 'department',
        fields: []
      }
    },
    status: 1
  })
  dialogVisible.value = true
}

// 编辑模板
const handleEdit = (row) => {
  currentTemplate.value = row
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除模板
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该模板吗？', '提示', {
      type: 'warning'
    })
    const res = await permissionTemplateApi.deleteTemplate(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete template error:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const method = currentTemplate.value ? 'updateTemplate' : 'createTemplate'
    const res = await permissionTemplateApi[method](
      currentTemplate.value?.id,
      formData
    )
    if (res.code === 200) {
      ElMessage.success(currentTemplate.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
    }
  } catch (error) {
    console.error('Save template error:', error)
    ElMessage.error('保存失败')
  }
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.template-list {
  height: 100%;
  margin: -20px;
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.search-bar {
  background: #fff;
  padding: 18px 0;
}

// 响应式处理
@media screen and (max-width: 768px) {
  .search-bar {
    .el-form--inline .el-form-item {
      margin-right: 0;
      width: 100%;
    }
  }
}
</style> 